package com.eco.netty;


import com.eco.constants.Constants;
import com.eco.utils.KndUtil;
import com.eco.utils.NettyCtxMap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;


@Data
@Slf4j
@EqualsAndHashCode(callSuper = true)
public class SensorHexHandler extends ChannelInboundHandlerAdapter {

    private GenericNettyClient nettyClient;
    private String host;
    private int port;
    private String clientId;

    public SensorHexHandler(GenericNettyClient nettyClient,String host, int port,String clientId) {
        this.nettyClient = nettyClient;
        this.host = host;
        this.port = port;
        this.clientId = clientId;
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE){
                ctx.channel().close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("传感器和灯控plc-tcp有新连接");
        NettyCtxMap.add(clientId, ctx);
        KndUtil.sendCommand(clientId, Constants.KND_TURN_ON);
    }



    @Override
    public void channelInactive(ChannelHandlerContext ctx)  {
        log.error("与传感器和灯控plc-tcp服务" + host + ":" + port + "连接断开");
        ctx.close();
        ctx.deregister();
        ctx.pipeline().remove(this);
        this.nettyClient.scheduleReconnect();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info("接收到继电器返回指令：{}", msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)  {
        log.error("与传感器和灯控plc-tcp服务连接异常！");
        ctx.close();
    }


}
